package com.xiangyi.teachingsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiangyi.teachingsystem.dao.GroupResMapper;
import com.xiangyi.teachingsystem.dao.GroupUserMapper;
import com.xiangyi.teachingsystem.dao.MessageMapper;
import com.xiangyi.teachingsystem.dao.UserGroupMapper;
import com.xiangyi.teachingsystem.entity.dto.GroupDto;
import com.xiangyi.teachingsystem.entity.dto.UserGroupTaskCourseDto;
import com.xiangyi.teachingsystem.entity.po.GroupRes;
import com.xiangyi.teachingsystem.entity.po.GroupUser;
import com.xiangyi.teachingsystem.entity.po.Message;
import com.xiangyi.teachingsystem.entity.po.UserGroup;
import com.xiangyi.teachingsystem.service.UserGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserGroupServiceImpl extends ServiceImpl<UserGroupMapper, UserGroup> implements UserGroupService {
    @Autowired
    UserGroupMapper userGroupMapper;
    @Autowired
    GroupUserMapper groupUserMapper;
    @Autowired
    MessageMapper messageMapper;
    @Autowired
    GroupResMapper groupResMapper;

    @Override
    public List<UserGroup> groupList(Integer taskId) {
        return userGroupMapper.groupList(taskId);
    }

    @Override
    @Transactional
    public void delGroup(Integer groupId) {
        groupUserMapper.delete(new QueryWrapper<GroupUser>().eq("group_id",groupId));

        messageMapper.delete(new QueryWrapper<Message>()
                .eq("group_id",groupId));

        groupResMapper.delete(new QueryWrapper<GroupRes>()
                .eq("group_id",groupId));

        userGroupMapper.deleteById(groupId);
    }

    @Override
    public List<UserGroupTaskCourseDto> getGroupsByUserId(Integer userId) {
        return userGroupMapper.getGroupsByUserId(userId);
    }

    @Override
    public List<GroupDto> listByUserAndTaskIds(Integer userId, Integer taskId) {
        return userGroupMapper.listByUserAndTaskIds(userId,taskId);
    }

    @Override
    public Object getInfoById(Integer groupId) {
        return userGroupMapper.getInfoById(groupId);
    }

    @Override
    @Transactional
    public void saveGroupAndLeader(UserGroup userGroup) {
        userGroupMapper.insert(userGroup);
        UserGroup saveGroupInfo = userGroupMapper.selectOne(new QueryWrapper<UserGroup>()
                .eq("task_id", userGroup.getTaskId())
                .eq("group_name", userGroup.getGroupName()));
        //将组长添加到课程
        GroupUser groupUser = new GroupUser();
        groupUser.setGroupId(saveGroupInfo.getId());
        groupUser.setUserId(userGroup.getLeaderId());
        groupUser.setLeaderSign(true);
        groupUserMapper.insert(groupUser);
    }
}
